<template>
  <div>
    <main-box one="商品管理" two="分类参数">
      <el-row>
        <el-alert title="注意:只允许为第三级分类设置相关属性!" type="warning" show-icon :closable="false"></el-alert>
      </el-row>
      <el-row class="cat_opt">
        <span>选择商品分类：&nbsp;</span>
        <el-cascader
          expand-trigger="hover"
          v-model="selectedValue"
          :options="cateList"
          :props="cateListProps"
          @change="cateListChanged"
          clearable
        ></el-cascader>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            size="mini"
            @click="addDialogVisible=true"
          >动态参数</el-button>

          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" style="width: 100%" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  @close="removeTag(i,scope.row)"
                >{{item}}</el-tag>
                <!-- tag与button 切换 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button  v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                >修改</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态成员" name="only">
          <el-button
            type="primary"
            @click="addDialogVisible=true"
            :disabled="isBtnDisabled"
            size="mini"
          >静态成员</el-button>
          <!-- 静态成员表格 -->
          <el-table :data="onlyTableData" style="width: 100%" border stripe>
            <!-- 展开行 -->
           <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  @close="removeTag(i,scope.row)"
                >{{item}}</el-tag>
                <!-- tag与button 切换 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button  v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                >修改</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </main-box>

    <!-- 添加对话框-->
    <el-dialog
      :title=" '添加'+titleTxet "
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addFormClosed"
    >
      <!-- 主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
        <el-form-item :label="titleTxet" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addFormChecked">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog
      :title=" '添加'+titleTxet "
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editFormClosed"
    >
      <!-- 主体区域 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item :label="titleTxet" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editChecked">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      cateList: [],
      cateListProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      selectedValue: [],
      activeName: "many",
      manyTableData: [],
      onlyTableData: [],
      addDialogVisible: false,
      addForm: {
        attr_name: ""
      },
      addFormRules: {
        attr_name: [
          { required: true, message: "请输入需要的参数", trigger: "blur" }
        ]
      },
      editDialogVisible: false,
      editForm: {
        attr_name: "",
        attr_id: 0,
        attr_sel: "many"
      },
      editFormRules: {
        attr_name: [
          { required: true, message: "请输入需要的参数", trigger: "blur" }
        ]
      },
    };
  },
  mounted() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      // console.log(res);
      if (res.meta.status != 200) {
        return this.$message.error("获取商品失败");
      }
      this.cateList = res.data;
    },
    cateListChanged() {
      if (this.selectedValue.length != 3) {
        return (this.selectedValue = []);
      }
      //   console.log(this.selectedValue);
      this.toggleCateList();
    },
    handleTabClick() {
      // console.log(this.activeName);
      this.toggleCateList();
    },
    async toggleCateList() {
      if (this.cateId) {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: this.activeName } }
        );
        if (res.meta.status != 200) {
          return this.$message.error("获取数据失败！");
        }
        // 将字符串变成数组
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
          item.inputVisible=false;
          item.inputValue=''
        });
        console.log(res);
        if (this.activeName == "many") {
          this.manyTableData = res.data;
        } else {
          this.onlyTableData = res.data;
        }
      }
    },
    addFormClosed() {
      this.$refs.addFormRef.resetFields();
    },
    addFormChecked() {
      this.$refs.addFormRef.validate(async v => {
        if (v) {
          const { data: res } = await this.$http.post(
            `categories/${this.cateId} /attributes`,
            { attr_name: this.addForm.attr_name, attr_sel: this.activeName }
          );
          // console.log(res);
          if (res.meta.status != 201) {
            return this.$message.error("添加参数失败");
          }
          this.$message.success("添加参数成功");
          this.addDialogVisible = false;
          this.toggleCateList();
        }
      });
    },
    editFormClosed() {
      this.$refs.editFormRef.resetFields();
    },
    showEditDialog(role) {
      this.editForm.attr_id = role.attr_id;
      this.editForm.attr_name = role.attr_name;
      this.editForm.attr_sel = role.attr_sel;
      // console.log(role);
      this.editDialogVisible = true;
    },
    async editChecked() {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
        {
          attr_name: this.editForm.attr_name,
          attr_sel: this.editForm.attr_sel
        }
      );
      // console.log(res);
      if (res.meta.status != 200) {
        return this.$message.error("修改参数失败");
      }
      this.toggleCateList();
      this.editDialogVisible = false;
    },
    async handleInputConfirm(row){
        if(row.inputValue.trim().length==0){
          row.inputValue='';
          row.inputVisible=false;
          return;
        }
        row.attr_vals.push(row.inputValue);
        console.log(row.attr_vals);
        // 添加参数(编辑提交)
        const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals:row.attr_vals.join(' ')
        }
      );
      console.log(res);
      if (res.meta.status != 200) {
        return this.$message.error("修改参数失败");
      }
      this.$message.success("修改参数成功");
         row.inputVisible=false;
         row.inputValue=''; 
    },
    showInput(row){
      row.inputVisible=true;
       this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    async removeTag(i,row) {
        console.log(i,row);

         row.attr_vals.splice(i,1);
        // 调用删除参数的
         const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals:row.attr_vals.join(' ')
        }
      );
        if(res.meta.status!=200){
          return this.$message.error('删除失败')
        }
        this.$message.success('删除成功')
       
    }
  },
  computed: {
    //   会根据参与计算的成员的值得改变，自动进行重新计算
    isBtnDisabled() {
      if (this.selectedValue.length != 3) {
        return true;
      }
      return false;
    },
    cateId() {
      if (this.selectedValue.length == 3) {
        return this.selectedValue[2];
      } else {
        return null;
      }
    },
    titleTxet() {
      if (this.activeName == "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    }
  },
   watch: {
    // 监听级联菜单中的值 如果不为三级分类就重置 表格数据源
    selectedvalue: function(newValue) {
      //如果newValue为空
      if (newValue.length != 3) {
        this.manyData = [];
        this.onlyData = [];
      }
    }
  }
};
</script>
<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.input-new-tag{
   width: 90px;
    margin-left: 10px;
}

</style>